<template>
  <div class="card-type-form-page">
    <!-- Header -->
    <header class="page-header">
      <div class="container">
        <div class="header-content">
          <div class="header-left">
            <button @click="navigateBack" class="btn-back">
              ← 返回
            </button>
            <div class="header-info">
              <h1>卡片类型管理</h1>
              <p>创建和管理银行卡片类型</p>
            </div>
          </div>
          <div class="header-actions">
            <button 
              @click="openCreateForm" 
              class="btn-create"
              v-if="!isEditing"
            >
              + 新建卡片类型
            </button>
          </div>
        </div>
      </div>
    </header>

    <!-- Main Content -->
    <main class="page-main">
      <div class="container">
        <!-- Form Section -->
        <div class="form-section" v-if="showForm">
          <div class="form-card">
            <div class="form-header">
              <h2>{{ isEditing ? '编辑卡片类型' : '新建卡片类型' }}</h2>
              <button @click="closeForm" class="btn-close">&times;</button>
            </div>
            <form @submit.prevent="submitForm" class="card-type-form">
              <div class="form-row">
                <div class="form-group">
                  <label for="type_name">卡片类型名称 <span class="required">*</span></label>
                  <input 
                    type="text" 
                    id="type_name" 
                    v-model="formData.type_name" 
                    required
                    :class="{ 'error': errors.type_name }"
                    placeholder="请输入卡片类型名称"
                    maxlength="50"
                  />
                  <div v-if="errors.type_name" class="error-message">{{ errors.type_name }}</div>
                  <div class="field-hint">最多50个字符，必须唯一</div>
                </div>

                <div class="form-group">
                  <label for="card_category">卡片类别 <span class="required">*</span></label>
                  <select 
                    id="card_category" 
                    v-model="formData.card_category" 
                    required
                    :class="{ 'error': errors.card_category }"
                  >
                    <option value="" disabled>请选择卡片类别</option>
                    <option v-for="category in cardCategories" :key="category" :value="category">{{ category }}</option>
                  </select>
                  <div v-if="errors.card_category" class="error-message">{{ errors.card_category }}</div>
                </div>
              </div>

              <div class="form-group">
                <label for="description">描述</label>
                <textarea 
                  id="description" 
                  v-model="formData.description" 
                  :class="{ 'error': errors.description }"
                  placeholder="请输入卡片类型描述"
                  rows="3"
                  maxlength="255"
                ></textarea>
                <div v-if="errors.description" class="error-message">{{ errors.description }}</div>
                <div class="field-hint">最多255个字符</div>
              </div>

              <div class="form-row">
                <div class="form-group">
                  <label for="annual_fee">年费 (¥) <span class="required">*</span></label>
                  <div class="input-with-prefix">
                    <span class="input-prefix">¥</span>
                    <input 
                      type="number" 
                      id="annual_fee" 
                      v-model="formData.annual_fee" 
                      step="0.01" 
                      min="0"
                      required
                      :class="{ 'error': errors.annual_fee }"
                      placeholder="请输入年费"
                    />
                  </div>
                  <div v-if="errors.annual_fee" class="error-message">{{ errors.annual_fee }}</div>
                </div>

                <div class="form-group">
                  <label for="credit_limit">信用额度 (¥)</label>
                  <div class="input-with-prefix">
                    <span class="input-prefix">¥</span>
                    <input 
                      type="number" 
                      id="credit_limit" 
                      v-model="formData.credit_limit" 
                      step="0.01" 
                      min="0"
                      :class="{ 'error': errors.credit_limit }"
                      placeholder="请输入信用额度（借记卡可为空）"
                    />
                  </div>
                  <div v-if="errors.credit_limit" class="error-message">{{ errors.credit_limit }}</div>
                  <div class="field-hint">借记卡可留空，信用卡必填</div>
                </div>
              </div>

              <div class="form-row">
                <div class="form-group">
                  <label for="interest_rate">利率 (%) <span class="required">*</span></label>
                  <div class="input-with-suffix">
                    <input 
                      type="number" 
                      id="interest_rate" 
                      v-model="formData.interest_rate" 
                      step="0.01" 
                      min="0"
                      max="100"
                      required
                      :class="{ 'error': errors.interest_rate }"
                      placeholder="请输入利率"
                    />
                    <span class="input-suffix">%</span>
                  </div>
                  <div v-if="errors.interest_rate" class="error-message">{{ errors.interest_rate }}</div>
                </div>

                <div class="form-group">
                  <label for="reward_rate">奖励积分率 (%)</label>
                  <div class="input-with-suffix">
                    <input 
                      type="number" 
                      id="reward_rate" 
                      v-model="formData.reward_rate" 
                      step="0.01" 
                      min="0"
                      max="10"
                      :class="{ 'error': errors.reward_rate }"
                      placeholder="请输入奖励积分率"
                    />
                    <span class="input-suffix">%</span>
                  </div>
                  <div v-if="errors.reward_rate" class="error-message">{{ errors.reward_rate }}</div>
                  <div class="field-hint">每消费1元可获得的积分百分比</div>
                </div>
              </div>

              <!-- Card Features -->
              <div class="features-section">
                <h3>卡片特性</h3>
                <div class="features-grid">
                  <label class="feature-checkbox">
                    <input type="checkbox" v-model="formData.features.contactless_payment" />
                    <span class="checkmark"></span>
                    非接触式支付
                  </label>
                  <label class="feature-checkbox">
                    <input type="checkbox" v-model="formData.features.online_banking" />
                    <span class="checkmark"></span>
                    网上银行
                  </label>
                  <label class="feature-checkbox">
                    <input type="checkbox" v-model="formData.features.mobile_banking" />
                    <span class="checkmark"></span>
                    手机银行
                  </label>
                  <label class="feature-checkbox">
                    <input type="checkbox" v-model="formData.features.international_usage" />
                    <span class="checkmark"></span>
                    境外使用
                  </label>
                  <label class="feature-checkbox">
                    <input type="checkbox" v-model="formData.features.cash_advance" />
                    <span class="checkmark"></span>
                    现金预借
                  </label>
                  <label class="feature-checkbox">
                    <input type="checkbox" v-model="formData.features.installment_payment" />
                    <span class="checkmark"></span>
                    分期付款
                  </label>
                  <label class="feature-checkbox">
                    <input type="checkbox" v-model="formData.features.reward_program" />
                    <span class="checkmark"></span>
                    积分奖励
                  </label>
                  <label class="feature-checkbox">
                    <input type="checkbox" v-model="formData.features.travel_insurance" />
                    <span class="checkmark"></span>
                    旅行保险
                  </label>
                </div>
              </div>

              <div class="form-row">
                <div class="form-group">
                  <label for="minimum_income">最低收入要求 (¥)</label>
                  <div class="input-with-prefix">
                    <span class="input-prefix">¥</span>
                    <input 
                      type="number" 
                      id="minimum_income" 
                      v-model="formData.minimum_income" 
                      step="0.01" 
                      min="0"
                      :class="{ 'error': errors.minimum_income }"
                      placeholder="请输入最低收入要求"
                    />
                  </div>
                  <div v-if="errors.minimum_income" class="error-message">{{ errors.minimum_income }}</div>
                  <div class="field-hint">申请此卡片类型的最低月收入要求</div>
                </div>

                <div class="form-group">
                  <label for="status">状态</label>
                  <select 
                    id="status" 
                    v-model="formData.status"
                    :class="{ 'error': errors.status }"
                  >
                    <option v-for="status in cardStatuses" :key="status.value" :value="status.value">
                      {{ status.label }}
                    </option>
                  </select>
                  <div v-if="errors.status" class="error-message">{{ errors.status }}</div>
                </div>
              </div>

              <div class="form-actions">
                <button type="button" class="btn-cancel" @click="closeForm">取消</button>
                <button 
                  type="submit" 
                  class="btn-submit"
                  :disabled="isSubmitting"
                >
                  <span v-if="isSubmitting" class="loading-spinner"></span>
                  {{ isSubmitting ? '提交中...' : (isEditing ? '保存修改' : '创建卡片类型') }}
                </button>
              </div>
            </form>
          </div>
        </div>

        <!-- List Section -->
        <div class="list-section">
          <div class="list-header">
            <h2>卡片类型列表</h2>
            <div class="list-actions">
              <div class="search-box">
                <input 
                  type="text" 
                  v-model="searchQuery" 
                  placeholder="搜索卡片类型..." 
                  @input="handleSearch"
                />
                <span class="search-icon">🔍</span>
              </div>
              <button @click="refreshData" class="btn-refresh">
                刷新数据
              </button>
            </div>
          </div>

          <div class="table-container">
            <div v-if="isLoading" class="loading-state">
              <div class="loading-spinner large"></div>
              <p>正在加载数据...</p>
            </div>

            <div v-else-if="filteredCardTypes.length === 0" class="empty-state">
              <div class="empty-icon">💳</div>
              <h3>暂无卡片类型数据</h3>
              <p>点击"新建卡片类型"按钮创建新的卡片类型</p>
            </div>

            <table v-else class="data-table">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>类型名称</th>
                  <th>类别</th>
                  <th>年费</th>
                  <th>信用额度</th>
                  <th>利率</th>
                  <th>状态</th>
                  <th>创建时间</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="cardType in filteredCardTypes" :key="cardType.card_type_id">
                  <td>{{ cardType.card_type_id }}</td>
                  <td class="type-name">
                    <div class="card-type-info">
                      <span class="name">{{ cardType.type_name }}</span>
                      <span class="category-badge" :class="getCategoryClass(cardType.card_category)">
                        {{ cardType.card_category }}
                      </span>
                    </div>
                  </td>
                  <td>{{ cardType.card_category }}</td>
                  <td>¥{{ formatNumber(cardType.annual_fee) }}</td>
                  <td>
                    {{ cardType.credit_limit ? '¥' + formatNumber(cardType.credit_limit) : '-' }}
                  </td>
                  <td>{{ formatNumber(cardType.interest_rate) }}%</td>
                  <td>
                    <span 
                      class="status-badge" 
                      :class="getStatusClass(cardType.status)"
                    >
                      {{ getStatusLabel(cardType.status) }}
                    </span>
                  </td>
                  <td>{{ formatDateTime(cardType.created_at) }}</td>
                  <td class="actions-cell">
                    <button @click="editCardType(cardType)" class="btn-edit">
                      编辑
                    </button>
                    <button @click="confirmDelete(cardType)" class="btn-delete">
                      删除
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </main>

    <!-- Delete Confirmation Modal -->
    <div class="modal" v-if="showDeleteModal">
      <div class="modal-content delete-modal">
        <div class="modal-header">
          <h2>确认删除</h2>
          <button class="modal-close" @click="showDeleteModal = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="warning-icon">⚠️</div>
          <p>您确定要删除以下卡片类型吗？</p>
          
          <div class="delete-info">
            <div class="info-item">
              <span class="info-label">类型名称:</span>
              <span class="info-value">{{ cardTypeToDelete?.type_name }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">类别:</span>
              <span class="info-value">{{ cardTypeToDelete?.card_category }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">年费:</span>
              <span class="info-value">¥{{ formatNumber(cardTypeToDelete?.annual_fee) }}</span>
            </div>
          </div>
          
          <div class="warning-message">
            <p><strong>警告:</strong> 此操作不可逆，删除后数据将无法恢复。</p>
            <p>如果有关联的卡片使用此类型，删除可能会导致系统错误。</p>
          </div>
          
          <div class="form-actions">
            <button type="button" class="btn-cancel" @click="showDeleteModal = false">
              取消
            </button>
            <button 
              type="button" 
              class="btn-delete-confirm" 
              @click="deleteCardType"
              :disabled="isDeleting"
            >
              <span v-if="isDeleting" class="loading-spinner"></span>
              {{ isDeleting ? '删除中...' : '确认删除' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Success Notification -->
    <div class="notification success-notification" v-if="showSuccessNotification">
      <div class="notification-icon">✓</div>
      <div class="notification-content">
        <div class="notification-title">操作成功</div>
        <div class="notification-message">{{ successMessage }}</div>
      </div>
      <button class="notification-close" @click="showSuccessNotification = false">&times;</button>
    </div>

    <!-- Error Notification -->
    <div class="notification error-notification" v-if="showErrorNotification">
      <div class="notification-icon">✗</div>
      <div class="notification-content">
        <div class="notification-title">操作失败</div>
        <div class="notification-message">{{ errorMessage }}</div>
      </div>
      <button class="notification-close" @click="showErrorNotification = false">&times;</button>
    </div>

    <!-- Modal Overlay -->
    <div 
      class="modal-overlay" 
      v-if="showDeleteModal" 
      @click="showDeleteModal = false"
    ></div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';

// 响应式数据
const cardTypes = ref([]);
const filteredCardTypes = ref([]);
const searchQuery = ref('');
const isLoading = ref(false);
const isSubmitting = ref(false);
const isDeleting = ref(false);
const isEditing = ref(false);
const showForm = ref(false);
const showDeleteModal = ref(false);
const showSuccessNotification = ref(false);
const showErrorNotification = ref(false);
const successMessage = ref('');
const errorMessage = ref('');
const cardTypeToDelete = ref(null);

// 卡片类别选项
const cardCategories = [
  '信用卡',
  '借记卡',
  '预付卡',
  '商务卡',
  '学生卡',
  '白金卡',
  '钻石卡',
  '普通卡'
];

// 状态选项
const cardStatuses = [
  { value: 'Active', label: '启用' },
  { value: 'Inactive', label: '停用' },
  { value: 'Pending', label: '待审核' },
  { value: 'Suspended', label: '暂停' }
];

// 表单数据
const formData = reactive({
  card_type_id: null,
  type_name: '',
  card_category: '',
  description: '',
  annual_fee: '',
  credit_limit: '',
  interest_rate: '',
  reward_rate: '',
  minimum_income: '',
  status: 'Active',
  features: {
    contactless_payment: false,
    online_banking: false,
    mobile_banking: false,
    international_usage: false,
    cash_advance: false,
    installment_payment: false,
    reward_program: false,
    travel_insurance: false
  }
});

// 表单错误
const errors = reactive({});

// 模拟数据
const mockCardTypes = [
  {
    card_type_id: 1,
    type_name: '普通信用卡',
    card_category: '信用卡',
    description: '适合日常消费的基础信用卡',
    annual_fee: 100.00,
    credit_limit: 50000.00,
    interest_rate: 18.00,
    reward_rate: 1.00,
    minimum_income: 3000.00,
    status: 'Active',
    created_at: '2024-01-10T08:30:00Z',
    updated_at: '2024-01-10T08:30:00Z'
  },
  {
    card_type_id: 2,
    type_name: '白金信用卡',
    card_category: '白金卡',
    description: '高端客户专享，享受更多特权服务',
    annual_fee: 800.00,
    credit_limit: 200000.00,
    interest_rate: 15.00,
    reward_rate: 2.50,
    minimum_income: 15000.00,
    status: 'Active',
    created_at: '2024-01-11T09:15:00Z',
    updated_at: '2024-01-11T09:15:00Z'
  },
  {
    card_type_id: 3,
    type_name: '学生借记卡',
    card_category: '学生卡',
    description: '专为学生设计的借记卡，免年费',
    annual_fee: 0.00,
    credit_limit: null,
    interest_rate: 0.50,
    reward_rate: 0.50,
    minimum_income: 0.00,
    status: 'Active',
    created_at: '2024-01-12T10:20:00Z',
    updated_at: '2024-01-12T10:20:00Z'
  },
  {
    card_type_id: 4,
    type_name: '商务信用卡',
    card_category: '商务卡',
    description: '为企业客户提供的商务信用卡',
    annual_fee: 500.00,
    credit_limit: 500000.00,
    interest_rate: 16.00,
    reward_rate: 1.80,
    minimum_income: 10000.00,
    status: 'Active',
    created_at: '2024-01-13T14:45:00Z',
    updated_at: '2024-01-13T14:45:00Z'
  }
];

// 方法
async function fetchCardTypes() {
  isLoading.value = true;

  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 使用模拟数据
    cardTypes.value = [...mockCardTypes];
    filteredCardTypes.value = [...mockCardTypes];
    
  } catch (error) {
    console.error('获取卡片类型数据失败:', error);
    showError('获取卡片类型数据失败，请重试');
  } finally {
    isLoading.value = false;
  }
}

function handleSearch() {
  const query = searchQuery.value.toLowerCase().trim();

  filteredCardTypes.value = cardTypes.value.filter(cardType => {
    return cardType.type_name.toLowerCase().includes(query) ||
           cardType.card_category.toLowerCase().includes(query) ||
           (cardType.description && cardType.description.toLowerCase().includes(query)) ||
           cardType.card_type_id.toString().includes(query);
  });
}

function refreshData() {
  fetchCardTypes();
  searchQuery.value = '';
}

function openCreateForm() {
  isEditing.value = false;
  resetForm();
  showForm.value = true;
}

function editCardType(cardType) {
  isEditing.value = true;

  // 复制卡片类型数据到表单
  formData.card_type_id = cardType.card_type_id;
  formData.type_name = cardType.type_name;
  formData.card_category = cardType.card_category;
  formData.description = cardType.description || '';
  formData.annual_fee = cardType.annual_fee;
  formData.credit_limit = cardType.credit_limit;
  formData.interest_rate = cardType.interest_rate;
  formData.reward_rate = cardType.reward_rate;
  formData.minimum_income = cardType.minimum_income;
  formData.status = cardType.status;

  // 重置特性（在实际应用中应该从数据库加载）
  Object.keys(formData.features).forEach(key => {
    formData.features[key] = Math.random() > 0.5; // 模拟数据
  });

  errors.value = {};
  showForm.value = true;
}

function closeForm() {
  showForm.value = false;
  resetForm();
}

function resetForm() {
  formData.card_type_id = null;
  formData.type_name = '';
  formData.card_category = '';
  formData.description = '';
  formData.annual_fee = '';
  formData.credit_limit = '';
  formData.interest_rate = '';
  formData.reward_rate = '';
  formData.minimum_income = '';
  formData.status = 'Active';
  
  Object.keys(formData.features).forEach(key => {
    formData.features[key] = false;
  });
  
  errors.value = {};
}

function validateForm() {
  errors.value = {};
  let isValid = true;

  if (!formData.type_name.trim()) {
    errors.type_name = '请输入卡片类型名称';
    isValid = false;
  } else if (formData.type_name.length > 50) {
    errors.type_name = '卡片类型名称不能超过50个字符';
    isValid = false;
  } else if (!isEditing.value && cardTypes.value.some(type => type.type_name.toLowerCase() === formData.type_name.toLowerCase().trim())) {
    errors.type_name = '卡片类型名称已存在';
    isValid = false;
  } else if (isEditing.value && cardTypes.value.some(type => 
    type.type_name.toLowerCase() === formData.type_name.toLowerCase().trim() && 
    type.card_type_id !== formData.card_type_id)) {
    errors.type_name = '卡片类型名称已存在';
    isValid = false;
  }

  if (!formData.card_category) {
    errors.card_category = '请选择卡片类别';
    isValid = false;
  }

  if (formData.description && formData.description.length > 255) {
    errors.description = '描述不能超过255个字符';
    isValid = false;
  }

  if (formData.annual_fee === '') {
    errors.annual_fee = '请输入年费';
    isValid = false;
  } else if (isNaN(formData.annual_fee) || parseFloat(formData.annual_fee) < 0) {
    errors.annual_fee = '年费必须是非负数';
    isValid = false;
  }

  if (formData.credit_limit && (isNaN(formData.credit_limit) || parseFloat(formData.credit_limit) < 0)) {
    errors.credit_limit = '信用额度必须是非负数';
    isValid = false;
  }

  // 信用卡类别需要信用额度
  if ((formData.card_category === '信用卡' || formData.card_category === '白金卡' || formData.card_category === '钻石卡' || formData.card_category === '商务卡') && !formData.credit_limit) {
    errors.credit_limit = '此卡片类别需要设置信用额度';
    isValid = false;
  }

  if (formData.interest_rate === '') {
    errors.interest_rate = '请输入利率';
    isValid = false;
  } else if (isNaN(formData.interest_rate) || parseFloat(formData.interest_rate) < 0) {
    errors.interest_rate = '利率必须是非负数';
    isValid = false;
  } else if (parseFloat(formData.interest_rate) > 100) {
    errors.interest_rate = '利率不能超过100%';
    isValid = false;
  }

  if (formData.reward_rate && (isNaN(formData.reward_rate) || parseFloat(formData.reward_rate) < 0 || parseFloat(formData.reward_rate) > 10)) {
    errors.reward_rate = '奖励积分率必须在0-10%之间';
    isValid = false;
  }

  if (formData.minimum_income && (isNaN(formData.minimum_income) || parseFloat(formData.minimum_income) < 0)) {
    errors.minimum_income = '最低收入要求必须是非负数';
    isValid = false;
  }

  return isValid;
}

async function submitForm() {
  if (!validateForm()) {
    return;
  }

  isSubmitting.value = true;

  try {
    // 准备提交的数据
    const cardTypeData = {
      card_type_id: formData.card_type_id,
      type_name: formData.type_name.trim(),
      card_category: formData.card_category,
      description: formData.description.trim() || null,
      annual_fee: parseFloat(formData.annual_fee),
      credit_limit: formData.credit_limit ? parseFloat(formData.credit_limit) : null,
      interest_rate: parseFloat(formData.interest_rate),
      reward_rate: formData.reward_rate ? parseFloat(formData.reward_rate) : null,
      minimum_income: formData.minimum_income ? parseFloat(formData.minimum_income) : null,
      status: formData.status,
      features: { ...formData.features }
    };
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    if (isEditing.value) {
      // 更新现有卡片类型
      const index = cardTypes.value.findIndex(item => item.card_type_id === cardTypeData.card_type_id);
      if (index !== -1) {
        cardTypeData.updated_at = new Date().toISOString();
        cardTypes.value[index] = { ...cardTypes.value[index], ...cardTypeData };
      }
      
      showSuccess('卡片类型更新成功');
    } else {
      // 创建新卡片类型
      const newCardType = {
        ...cardTypeData,
        card_type_id: Math.max(...cardTypes.value.map(item => item.card_type_id)) + 1,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      };
      
      cardTypes.value.push(newCardType);
      showSuccess('卡片类型创建成功');
    }
    
    // 刷新过滤后的列表
    handleSearch();
    
    // 关闭表单
    closeForm();
    
  } catch (error) {
    console.error('提交卡片类型数据失败:', error);
    showError('提交卡片类型数据失败，请重试');
  } finally {
    isSubmitting.value = false;
  }
}

function confirmDelete(cardType) {
  cardTypeToDelete.value = cardType;
  showDeleteModal.value = true;
}

async function deleteCardType() {
  if (!cardTypeToDelete.value) {
    return;
  }

  isDeleting.value = true;

  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 模拟删除
    cardTypes.value = cardTypes.value.filter(
      item => item.card_type_id !== cardTypeToDelete.value.card_type_id
    );
    
    // 刷新过滤后的列表
    handleSearch();
    
    showSuccess('卡片类型删除成功');
    showDeleteModal.value = false;
    
  } catch (error) {
    console.error('删除卡片类型失败:', error);
    showError('删除卡片类型失败，请重试');
  } finally {
    isDeleting.value = false;
  }
}

function showSuccess(message) {
  successMessage.value = message;
  showSuccessNotification.value = true;

  // 自动隐藏通知
  setTimeout(() => {
    showSuccessNotification.value = false;
  }, 3000);
}

function showError(message) {
  errorMessage.value = message;
  showErrorNotification.value = true;

  // 自动隐藏通知
  setTimeout(() => {
    showErrorNotification.value = false;
  }, 5000);
}

function navigateBack() {
  console.log('返回上一页');
  // router.go(-1) 或 router.push('/admin')
}

function getCategoryClass(category) {
  const classes = {
    '信用卡': 'category-credit',
    '借记卡': 'category-debit',
    '预付卡': 'category-prepaid',
    '商务卡': 'category-business',
    '学生卡': 'category-student',
    '白金卡': 'category-platinum',
    '钻石卡': 'category-diamond',
    '普通卡': 'category-regular'
  };
  return classes[category] || 'category-default';
}

function getStatusClass(status) {
  const classes = {
    'Active': 'status-active',
    'Inactive': 'status-inactive',
    'Pending': 'status-pending',
    'Suspended': 'status-suspended'
  };
  return classes[status] || 'status-default';
}

function getStatusLabel(status) {
  const labels = {
    'Active': '启用',
    'Inactive': '停用',
    'Pending': '待审核',
    'Suspended': '暂停'
  };
  return labels[status] || status;
}

function formatNumber(value) {
  if (value === null || value === undefined) return '0.00';
  return new Intl.NumberFormat('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(value);
}

function formatDateTime(dateString) {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).format(date);
}

// 组件挂载时初始化
onMounted(() => {
  fetchCardTypes();
});
</script>

<style scoped>
.card-type-form-page {
  min-height: 100vh;
  background-color: #f8fafc;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1rem;
}

/* Header */
.page-header {
  background-color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.btn-back {
  background-color: #f3f4f6;
  color: #374151;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-back:hover {
  background-color: #e5e7eb;
}

.header-info h1 {
  font-size: 1.75rem;
  font-weight: 700;
  color: #1e40af;
  margin: 0 0 0.25rem 0;
}

.header-info p {
  color: #6b7280;
  margin: 0;
  font-size: 0.875rem;
}

.btn-create {
  background-color: #1e40af;
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 0.375rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-create:hover {
  background-color: #1e3a8a;
}

/* Main Content */
.page-main {
  padding: 2rem 0;
}

/* Form Section */
.form-section {
  margin-bottom: 2rem;
}

.form-card {
  background-color: white;
  border-radius: 0.75rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

.form-header h2 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1e40af;
  margin: 0;
}

.btn-close {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #6b7280;
}

.card-type-form {
  padding: 1.5rem;
}

.form-row {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.form-group {
  flex: 1;
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  font-size: 0.875rem;
  font-weight: 500;
  margin-bottom: 0.5rem;
  color: #374151;
}

.required {
  color: #ef4444;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  transition: border-color 0.2s;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  border-color: #1e40af;
  outline: none;
  box-shadow: 0 0 0 2px rgba(30, 64, 175, 0.1);
}

.form-group input.error,
.form-group select.error,
.form-group textarea.error {
  border-color: #ef4444;
}

.error-message {
  color: #ef4444;
  font-size: 0.75rem;
  margin-top: 0.25rem;
}

.field-hint {
  color: #6b7280;
  font-size: 0.75rem;
  margin-top: 0.25rem;
}

.input-with-prefix,
.input-with-suffix {
  position: relative;
}

.input-prefix {
  position: absolute;
  left: 0.75rem;
  top: 0.75rem;
  color: #6b7280;
}

.input-suffix {
  position: absolute;
  right: 0.75rem;
  top: 0.75rem;
  color: #6b7280;
}

.input-with-prefix input {
  padding-left: 1.5rem;
}

.input-with-suffix input {
  padding-right: 1.5rem;
}

/* Features Section */
.features-section {
  margin-bottom: 1.5rem;
  padding: 1.5rem;
  background-color: #f8fafc;
  border-radius: 0.5rem;
  border-left: 4px solid #1e40af;
}

.features-section h3 {
  font-size: 1rem;
  font-weight: 600;
  color: #1e40af;
  margin: 0 0 1rem 0;
}

.features-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
}

.feature-checkbox {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  font-size: 0.875rem;
  color: #374151;
}

.feature-checkbox input[type="checkbox"] {
  width: auto;
  margin: 0;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1.5rem;
}

.btn-cancel {
  background-color: white;
  color: #374151;
  border: 1px solid #d1d5db;
  padding: 0.75rem 1.5rem;
  border-radius: 0.375rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-cancel:hover {
  background-color: #f9fafb;
}

.btn-submit {
  background-color: #1e40af;
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 0.375rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.btn-submit:hover:not(:disabled) {
  background-color: #1e3a8a;
}

.btn-submit:disabled {
  background-color: #9ca3af;
  cursor: not-allowed;
}

/* List Section */
.list-section {
  background-color: white;
  border-radius: 0.75rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

.list-header h2 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1e40af;
  margin: 0;
}

.list-actions {
  display: flex;
  gap: 1rem;
}

.search-box {
  position: relative;
}

.search-box input {
  padding: 0.75rem 1rem 0.75rem 2.5rem;
  border: 1px solid #d1d5db;
  border-radius: 0.375rem;
  font-size: 0.875rem;
}

.search-box input:focus {
  border-color: #1e40af;
  outline: none;
  box-shadow: 0 0 0 2px rgba(30, 64, 175, 0.1);
}

.search-icon {
  position: absolute;
  left: 0.75rem;
  top: 50%;
  transform: translateY(-50%);
  color: #6b7280;
}

.btn-refresh {
  background-color: #f3f4f6;
  color: #374151;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-refresh:hover {
  background-color: #e5e7eb;
}

/* Table Container */
.table-container {
  overflow-x: auto;
}

.loading-state,
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 4rem 2rem;
  text-align: center;
  color: #6b7280;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
}

.empty-state h3 {
  font-size: 1.25rem;
  font-weight: 600;
  margin: 0 0 0.5rem 0;
  color: #374151;
}

.loading-spinner {
  width: 1rem;
  height: 1rem;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-spinner.large {
  width: 2rem;
  height: 2rem;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* Data Table */
.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 1rem;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
}

.data-table th {
  background-color: #f9fafb;
  font-weight: 600;
  color: #374151;
  font-size: 0.875rem;
}

.data-table tbody tr:hover {
  background-color: #f9fafb;
}

.card-type-info {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.card-type-info .name {
  font-weight: 500;
  color: #1e40af;
}

.category-badge {
  display: inline-block;
  padding: 0.125rem 0.5rem;
  border-radius: 9999px;
  font-size: 0.75rem;
  font-weight: 500;
}

.category-credit {
  background-color: #fef3c7;
  color: #92400e;
}

.category-debit {
  background-color: #dbeafe;
  color: #1e40af;
}

.category-prepaid {
  background-color: #e0e7ff;
  color: #3730a3;
}

.category-business {
  background-color: #f3e8ff;
  color: #6b21a8;
}

.category-student {
  background-color: #dcfce7;
  color: #166534;
}

.category-platinum {
  background-color: #f1f5f9;
  color: #475569;
}

.category-diamond {
  background-color: #fdf2f8;
  color: #be185d;
}

.category-regular {
  background-color: #f9fafb;
  color: #374151;
}

.status-badge {
  display: inline-block;
  padding: 0.25rem 0.5rem;
  border-radius: 9999px;
  font-size: 0.75rem;
  font-weight: 500;
}

.status-active {
  background-color: #dcfce7;
  color: #166534;
}

.status-inactive {
  background-color: #fee2e2;
  color: #991b1b;
}

.status-pending {
  background-color: #fef3c7;
  color: #92400e;
}

.status-suspended {
  background-color: #f3f4f6;
  color: #4b5563;
}

.actions-cell {
  white-space: nowrap;
}

.btn-edit,
.btn-delete {
  padding: 0.25rem 0.75rem;
  border-radius: 0.25rem;
  font-size: 0.75rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-edit {
  background-color: #dbeafe;
  color: #1e40af;
  border: none;
  margin-right: 0.5rem;
}

.btn-edit:hover {
  background-color: #bfdbfe;
}

.btn-delete {
  background-color: #fee2e2;
  color: #dc2626;
  border: none;
}

.btn-delete:hover {
  background-color: #fecaca;
}

/* Modal Styles */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 100;
}

.modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 101;
  width: 90%;
  max-width: 500px;
}

.modal-content {
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.delete-modal {
  max-width: 500px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h2 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1e40af;
  margin: 0;
}

.modal-close {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #6b7280;
}

.modal-body {
  padding: 1.5rem;
}

/* Delete Modal Styles */
.warning-icon {
  font-size: 3rem;
  color: #f59e0b;
  text-align: center;
  margin-bottom: 1rem;
}

.delete-info {
  margin: 1.5rem 0;
  padding: 1rem;
  background-color: #f9fafb;
  border-radius: 0.375rem;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.5rem;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-label {
  font-weight: 500;
  color: #4b5563;
}

.warning-message {
  margin: 1.5rem 0;
  padding: 1rem;
  background-color: #fff5f5;
  border-left: 4px solid #ef4444;
  color: #991b1b;
  font-size: 0.875rem;
}

.btn-delete-confirm {
  background-color: #ef4444;
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 0.375rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.btn-delete-confirm:hover:not(:disabled) {
  background-color: #dc2626;
}

.btn-delete-confirm:disabled {
  background-color: #9ca3af;
  cursor: not-allowed;
}

/* Notification Styles */
.notification {
  position: fixed;
  bottom: 2rem;
  right: 2rem;
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  border-radius: 0.5rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  z-index: 99;
  max-width: 400px;
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.success-notification {
  background-color: #dcfce7;
  border-left: 4px solid #059669;
}

.error-notification {
  background-color: #fee2e2;
  border-left: 4px solid #dc2626;
}

.notification-icon {
  font-size: 1.5rem;
}

.success-notification .notification-icon {
  color: #059669;
}

.error-notification .notification-icon {
  color: #dc2626;
}

.notification-content {
  flex: 1;
}

.notification-title {
  font-weight: 600;
  margin-bottom: 0.25rem;
}

.success-notification .notification-title {
  color: #166534;
}

.error-notification .notification-title {
  color: #991b1b;
}

.notification-message {
  font-size: 0.875rem;
}

.success-notification .notification-message {
  color: #166534;
}

.error-notification .notification-message {
  color: #991b1b;
}

.notification-close {
  background: none;
  border: none;
  font-size: 1.25rem;
  cursor: pointer;
  color: #6b7280;
}

/* Responsive Design */
@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
  }
  
  .list-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }

  .list-actions {
    width: 100%;
    flex-direction: column;
  }

  .search-box {
    width: 100%;
  }

  .search-box input {
    width: 100%;
  }

  .btn-refresh {
    width: 100%;
  }

  .data-table {
    font-size: 0.875rem;
  }

  .data-table th,
  .data-table td {
    padding: 0.75rem 0.5rem;
  }

  .form-actions {
    flex-direction: column;
  }

  .btn-cancel,
  .btn-submit,
  .btn-delete-confirm {
    width: 100%;
  }

  .features-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .header-content {
    flex-direction: column;
    gap: 1rem;
    text-align: center;
  }

  .header-left {
    flex-direction: column;
  }

  .notification {
    left: 1rem;
    right: 1rem;
    max-width: none;
  }
}
</style>
